package repositories

import (
	"SmartSearch/internal/models"
	"SmartSearch/internal/responses"
	"SmartSearch/pkg/database"
	"fmt"
	"time"
)

type DeviceRepository struct {
}

func (r *DeviceRepository) Add(device *models.Device) error {
	device.CreatedDate = time.Now()
	return database.DB.Create(&device).Error
}

func (r *DeviceRepository) Del(id int64) error {
	return database.DB.Delete(&models.Device{}, id).Error
}

func (r *DeviceRepository) FindById(id int64) (*models.Device, error) {
	var device models.Device
	err := database.DB.First(&device, id).Error
	return &device, err
}
func (r *DeviceRepository) FindByIds(ids []int64) []*models.Device {
	var device []*models.Device
	database.DB.Where("id IN ?", ids).Find(&device)
	return device
}

func (r *DeviceRepository) FindBySn(sn string) *models.Device {
	var device *models.Device
	database.DB.Where("sn = ?", sn).First(&device)
	return device
}

func (r *DeviceRepository) GetList(name string, enable *bool, current int32, pageSize int32) *responses.Page {
	var total int64
	var data []*models.Device
	where := fmt.Sprintf("name LIKE '%s'", "%"+name+"%")
	if enable != nil {
		where += fmt.Sprintf(" AND enable = %t", *enable)
	}
	// 此处用了PostForm的请求方法
	tx := database.DB.Debug().Model(models.Role{}).Where(where) // 查询对应的数据库表
	// 此时的total是查询到的总数
	if err := tx.Count(&total).Error; err != nil {
		fmt.Println("获取总数错误" + err.Error())
		return nil
	}
	offset := (current - 1) * pageSize
	if err := tx.Order("id DESC").Offset(int(offset)).Limit(int(pageSize)).Find(&data).Error; err != nil {
		return nil
	}
	return &responses.Page{
		Current:  current,
		PageSize: pageSize,
		Total:    total,
		Content:  data,
	}
}

func (r *DeviceRepository) Update(device *models.Role) error {
	return database.DB.Save(&device).Error
}
